#pragma once
#include "MountWidget.h"
#include "./ui_widget.h"

#include <QFileDialog>
#include <QCoreApplication>
#include <QStorageInfo>
#include <QDebug>
#include <windows.h>
#include <QEvent>
#include <QProcess>
#include <QMessageBox>
#include <QThread>
#include <windows.h>
#include "AuditPlanFun.h"
#include "DisplayMainwindow.h"
#include "LoginDialog.h"
#include <QTimer>
#include "UdiskInspection.h"
#include "ferryfs.h"
#include "utils.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Widget::updateDisplay);
    timer->start(1000); // 每秒触发一次
    //标题修改
    setWindowTitle("审计移动存储安全平台");
    setWindowIcon(QIcon(":/icons/images/Upan2.png"));
    this->setContentsMargins(0, 0, 0, 0);

    ui->groupBox->setStyleSheet("QGroupBox { border: none; "
                                "margin-top: 1.5ex; }");
    ui->groupBox_2->setStyleSheet("QGroupBox { background-color: white; "
                                  "border: none; "
                                  "margin-top: 1.5ex; }");

    int groupBoxWidth = ui->groupBox_3->width();
    int groupBoxHeight = ui->groupBox_3->height();
    // 加载背景图片
    QPixmap pixmap11(":/icons/images/login.png");
    // 动态调整背景图片的大小以适应 GroupBox
    QPixmap scaledPixmap = pixmap11.scaled(groupBoxWidth, groupBoxHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    // 将 QPixmap 对象转换为字符串路径
    QString scaledPixmapPath = QDir::tempPath() + "/scaledLoginImage.png";
    scaledPixmap.save(scaledPixmapPath);
    // 将背景图片设置为 GroupBox 的背景
    ui->groupBox_3->setStyleSheet(QString("QGroupBox {"
                                          "background-image: url(:/icons/images/login.png);"
                                          "background-position: center center;"
                                          "background-repeat: repeat;" // 设置平铺背景图片
                                          "border: none; "
                                          "margin-top: 1.5ex; "
                                          "}"
                                          "#groupBox_3 {"
                                          "background-image: url(%1);" // 设置动态调整大小的背景图片
                                          "}").arg(scaledPixmapPath));

    // 创建布局管理器
    AnalogClock *analogClock = new AnalogClock(this);
    QVBoxLayout *groupLayout = new QVBoxLayout;
    groupLayout->addWidget(analogClock);
    ui->groupBox_3->setLayout(groupLayout);

    QPixmap pixmap(":/icons/images/logo.png");
//    ui->label_5->setPixmap(pixmap);
//    ui->label_5->setScaledContents(true);

    ui->label_2->setText("技术支持单位: \n西安电子科技大学青岛计算技术研究院");
    ui->label_2->setAlignment(Qt::AlignCenter);

    ui->checkBox_AutMount->setStyleSheet("QCheckBox::indicator:checked { background-color: #E91E63; border-radius: 2px;}");

    QString buttonStyle = "QPushButton { background-color: #ADD8E6; border-radius: 8px; }"
                          "QPushButton:pressed { background-color: #6FAAD8; }";
    // 应用样式表
    ui->btnMount->setStyleSheet(buttonStyle);
    ui->btnMount_2->setStyleSheet(buttonStyle);

    ui->comboBox_Upan->setStyleSheet("QComboBox { border: 1px solid #CCCCCC; background-color: transparent; border-radius: 5px; }"
                                     "QComboBox:focus { border: 1px solid green; }"
                                     "QComboBox:hover { border: 1px solid green; }"
                                     "QComboBox:pressed { border: 1px solid green; }");


    // 安装事件过滤器
    installEventFilter(this);

    connect(this, &Widget::showEvent, this, &Widget::initializeComboBox);

    QObject::connect(ui->comboBox_Upan, &QComboBox::currentTextChanged, [&]() {
        // 检查QComboBox和文本内容是否为空
        if (!ui->comboBox_Upan->currentText().isEmpty()) {
            ui->btnMount->setEnabled(true);  // 启用QPushButton
            ui->btnMount_2->setEnabled(true);
        } else {
            ui->btnMount->setEnabled(false); // 禁用QPushButton
            ui->btnMount_2->setEnabled(false);
        }
    });

    connect(this, &Widget::widgetClicked, this, [=]() {
        initializeComboBox();
    });


//    connect(cust, &CustomWindow::displayClosed, this, [=]() {
//        ui->comboBox_Upan->clear();
//    });

}

QStringList Widget::MountPathList;

Widget::~Widget()
{
    delete ui;
}

bool Widget::isRemovableDrive(const QString &drivePath)
{
    UINT driveType = GetDriveType(reinterpret_cast<const TCHAR*>(drivePath.utf16()));
    return driveType == DRIVE_REMOVABLE;
}

void Widget::detectUsbChange()
{
    while(true){
        int num1 = 0;
        QList<QStorageInfo> storageList = QStorageInfo::mountedVolumes();

        ui->comboBox_Upan->clear();
        // 遍历存储设备列表
        foreach (const QStorageInfo &storage, storageList) {
            // 判断设备是否为可移动设备
            if (storage.isValid() && storage.isReady()) {
                QString drivePath = storage.rootPath();
                if (isRemovableDrive(drivePath)) {
                    num1++;
                }
            }
        }
        int num2 = ui->comboBox_Upan->count();
        if(num1 != num2){
            initializeComboBox();
        }
    }
}
void Widget::Auto_DisMount(){
    QString processName = "app.exe";
    QString command1 = "tasklist";
    QProcess process;
    QStringList arguments1;
    arguments1 << "/FI" << QString("IMAGENAME eq %1").arg(processName);

    process.start(command1, arguments1);
    process.waitForFinished();
    QByteArray output = process.readAllStandardOutput();
    QString outputStr = QString::fromLocal8Bit(output);

    if (outputStr.contains(processName)) {
        qDebug() << processName << "正在运行";
    } else {
        return;
    }


    QString program = "taskkill";
    QStringList arguments;
    arguments << "/F" << "/IM" << "app.exe";


    process.start(program, arguments);
    process.waitForFinished();
    // 获取命令执行的输出结果
    output = process.readAllStandardOutput();
    QByteArray error = process.readAllStandardError();

    // 打印输出和错误信息
    Widget::MountPathList.clear();
    ui->comboBox_Upan->clear();
    cust->close();
}



void Widget::updateDisplay()
{
    // 获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();
    // 格式化时间为字符串，如 "yyyy-MM-dd hh:mm:ss"
    QString timeString = currentTime.toString("yyyy-MM-dd hh:mm:ss");
    QDateTime dateTime = QDateTime::fromString(timeString, "yyyy-MM-dd hh:mm:ss");
    ui->label_7->setText(dateTime.toString("yyyy年MM月dd日"));
    ui->label_7->setStyleSheet("color: white;");
    ui->label_hm->setText(dateTime.toString("hh:mm"));
    ui->label_hm->setStyleSheet("color: white;");
    ui->label_s->setText(dateTime.toString("ss"));
    ui->label_s->setStyleSheet("color: white;");

    QLocale locale(QLocale::Chinese);
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QLocale chineseLocale(QLocale::Chinese);

    // 将当前日期时间格式化为只包含星期几的字符串
    QString chineseDayOfWeek = chineseLocale.toString(currentDateTime.date(), "dddd");
    ui->label_D->setText(chineseDayOfWeek);
    ui->label_D->setStyleSheet("color: white;");


    if(isLogin == true){
        initializeComboBox();
        if(ui->checkBox_AutMount->isChecked()){
            Auto_Mount();
        }
        foreach (const QString &drivePath, drivePathList) {
            bool isInserted = IsUsbDriveInserted(drivePath);
            if (!isInserted)
            {
                drivePathList.removeOne(drivePath);
                qDebug()<<"U盘:"<<drivePath<<"   已拔出。";
                Auto_DisMount();
            }
        }
    }
}

bool Widget::getLogin()
{
    return isLogin;
}

void Widget::setLogin(bool value)
{
    isLogin = value;
}

class MyThread : public QThread
{
public:
    QString m_data;
    MyThread(QString data) : m_data(data) {}
    void run() override
    {
        UsbEncrypt::AuditFun audit(m_data);
        //audit.insertAuditInfo();
    }
};

class MyThread1 : public QThread
{
public:
    QString m_data;
    MyThread1(QString data, QString connection){
        m_data = data;
    }
    void run() override
    {
        //UsbEncrypt::AuditFun audit(m_data);
        //audit.insertAuditInfo();
        ferryfs->connectUdiskDB(QString("ferrylog2"));
        ferryfs->writeAuditInfoToDB();
        ferryfs->readAuditInfoFromDB();
        ferryfs->closeDB();
        // ferryLog->m_db = QSqlDatabase::database("ferrylog");
    }
};

void Widget::Auto_Mount()
{
    QString str2= "C:/usb1";
    QList<QStorageInfo> storageList = QStorageInfo::mountedVolumes();
    //int itemCount = storageList.size();
    int i = 0;
    // 遍历存储设备列表
    foreach (const QStorageInfo &storage, storageList) {
        // 判断设备是否为可移动设备
        if (storage.isValid() && storage.isReady()) {
            QString drivePath = storage.rootPath();
            if (isRemovableDrive(drivePath)) {
                if(!drivePathList.contains(drivePath)){
                    drivePathList.append(drivePath);

                    //尝试获取摆渡盘检验码
                    QString filePath = drivePath + "/.db/ferrylog";
                    QFile file(filePath);
                    ferryfs =  new Ferryfs(drivePath);
                    ferryLog = new FerryLog();
                    ferryfs->connectUdiskDB(QString("ferrtlog1"));
                    QString defaultPassword = ferryfs->getDefaultPassword();
                    QString password = ferryfs->readPasswordFromDB();
                    ferryfs->closeDB();
                    if(file.exists() && password != defaultPassword){
                        MyD = new MyDialog(drivePath);
                        connect(MyD, &MyDialog::judgmentResult, this, &Widget::onUpdateFromSecondWindow);
                        MyD->show();
                    }
                    else{
                        Widget::MountPathList.append(drivePath);
                        QString str1=drivePath;
                        i++;
                        str2.append(QString::number(i));

                        // 创建 QProcess 对象
                        QProcess process;
                        QString program = "./app";
                        QStringList arguments;
                        arguments << str1 << str2;
                        process.start(program, arguments);
                        process.waitForFinished();
                        QByteArray output = process.readAllStandardOutput();
                        QByteArray error = process.readAllStandardError();
                        qDebug() << "Output:" << output;
                        qDebug() << "Error:" << error;

                        cust = new CustomWindow(str2);
                        cust->show();

                        MyThread thread(drivePath1);  // 创建线程时传入参数
                        thread.start();
                        thread.wait();

                        MyThread1 thread1(drivePath, "ferrylog");
                        thread1.start();
                        thread1.wait();
                    }
                }

            }
        }
    }
}

bool Widget::IsUsbDriveInserted(const QString &DrivePath)
{
    UINT driveType = GetDriveTypeA(DrivePath.toStdString().c_str());  // 这里假设U盘插入后会被分配到F盘
    return (driveType == DRIVE_REMOVABLE);
}

void Widget::onUpdateFromSecondWindow(bool result)
{
    if(result){
        qDebug()<<"awerfsretgrestgrw";
        QString str1=ui->comboBox_Upan->currentText();
        if(!Widget::MountPathList.contains(str1)){
            Widget::MountPathList.append(str1);
            QString str2="C:/usb1";
            qDebug() << "str1 = " << str1.toStdString().c_str();
            qDebug() << "str2 = " << str2.toStdString().c_str();

            // 创建 QProcess 对象
            QProcess process;
            QString program = "./app";
            QStringList arguments;
            arguments << str1 << str2;
            // 启动进程并传递命令和参数
            process.start(program, arguments);

            // 等待进程完成
            process.waitForFinished();
            // 获取命令执行的输出结果
            QByteArray output = process.readAllStandardOutput();
            QByteArray error = process.readAllStandardError();

            // 打印输出和错误信息
            qDebug() << "Output:" << output;
            qDebug() << "Error:" << error;

            QMessageBox::information(nullptr, "成功", "操作成功完成！");

            cust  = new CustomWindow(str2);
            cust->show();
            MyThread1 thread(drivePath1, "connection1");  // 创建线程时传入参数
            thread.start();
            thread.wait();
        }
        else{
            QMessageBox::information(nullptr, "挂载失败", "该设备已挂载！");
        }
    }
}

void Widget::on_btnMount_clicked()
{
    QString str1=ui->comboBox_Upan->currentText();
    //尝试获取摆渡盘检验码
    QString filePath = str1 + "/.db";
    QFile file(filePath);
    ferryfs->connectUdiskDB(QString("ferrylog2"));
    QString defaultPassword = ferryfs->getDefaultPassword();
    QString password = ferryfs->readPasswordFromDB();
    ferryfs->closeDB();
    if(file.exists() && password != defaultPassword){
        MyD = new MyDialog(str1);
        connect(MyD, &MyDialog::judgmentResult, this, &Widget::onUpdateFromSecondWindow);
        MyD->show();
    }
    else{
        if(!Widget::MountPathList.contains(str1)){
            Widget::MountPathList.append(str1);
            QString str2="C:/usb1";
            qDebug() << "str1 = " << str1.toStdString().c_str();
            qDebug() << "str2 = " << str2.toStdString().c_str();

            // 创建 QProcess 对象
            QProcess process;
            QString program = "./app";
            QStringList arguments;
            arguments << str1 << str2;
            // 启动进程并传递命令和参数
            process.start(program, arguments);

            // 等待进程完成
            process.waitForFinished();
            // 获取命令执行的输出结果
            QByteArray output = process.readAllStandardOutput();
            QByteArray error = process.readAllStandardError();

            // 打印输出和错误信息
            qDebug() << "Output:" << output;
            qDebug() << "Error:" << error;

            QMessageBox::information(nullptr, "成功", "操作成功完成！");

            cust = new CustomWindow(str2);
            cust->show();

            MyThread thread(drivePath1);  // 创建线程时传入参数
            thread.start();
            thread.wait();

            MyThread1 thread1(drivePath1, "ferrylog2");
            thread1.start();
            thread1.wait();
        }
        else{
            QMessageBox::information(nullptr, "挂载失败", "该设备已挂载！");
        }
    }

}
//void Widget::on_btnMount_clicked()
//{
//    QString str1=ui->comboBox_Upan->currentText();
//    if(!Widget::MountPathList.contains(str1)){
//        Widget::MountPathList.append(str1);
//        QString str2="C:/usb1";
//        qDebug() << "str1 = " << str1.toStdString().c_str();
//        qDebug() << "str2 = " << str2.toStdString().c_str();

//        // 创建 QProcess 对象
//        QProcess process;
//        QString program = "./app";
//        QStringList arguments;
//        arguments << str1 << str2;
//        // 启动进程并传递命令和参数
//        process.start(program, arguments);

//        // 等待进程完成
//        process.waitForFinished();
//        // 获取命令执行的输出结果
//        QByteArray output = process.readAllStandardOutput();
//        QByteArray error = process.readAllStandardError();

//        // 打印输出和错误信息
//        qDebug() << "Output:" << output;
//        qDebug() << "Error:" << error;

//        QMessageBox::information(nullptr, "成功", "操作成功完成！");
//        //隐藏目录
//        //    QString directoryPath = "D:/usb";
//        //    wchar_t* widePath = new wchar_t[directoryPath.length() + 1];
//        //    directoryPath.toWCharArray(widePath);
//        //    widePath[directoryPath.length()] = '\0';

//        //    DWORD attributes = GetFileAttributesW(widePath);
//        //    if (attributes != INVALID_FILE_ATTRIBUTES) {
//        //        SetFileAttributesW(widePath, attributes | FILE_ATTRIBUTE_HIDDEN);
//        //    }

//        //    delete[] widePath;
//        //打开目录





//        cust = new CustomWindow(str2);
//        //cust->setPath(str2);
//        cust->show();

//        //    UsbEncrypt::AuditFun audit(drivePath1);
//        //    audit.insertAuditInfo();
//        MyThread thread(drivePath1);  // 创建线程时传入参数
//        thread.start();
//        thread.wait();
//    }
//    else{
//        QMessageBox::information(nullptr, "挂载失败", "该设备已挂载！");
//    }

//}



void Widget::initializeComboBox()
{
    // 获取所有可用的存储设备信息
    QList<QStorageInfo> storageList = QStorageInfo::mountedVolumes();

    ui->comboBox_Upan->clear();
    // 遍历存储设备列表
    foreach (const QStorageInfo &storage, storageList) {
        // 判断设备是否为可移动设备
        if (storage.isValid() && storage.isReady()) {
            QString drivePath = storage.rootPath();
            if (isRemovableDrive(drivePath)) {
                ui->comboBox_Upan->addItem(storage.rootPath());
                qDebug() << "U盘已插入：" << drivePath;
                this->drivePath1 = drivePath;
            }
        }
    }
}


void Widget::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    initializeComboBox();
}

bool Widget::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress)
    {
        // 发送widgetClicked信号
        emit widgetClicked();
    }

    // 继续处理其他事件
    return QWidget::eventFilter(object, event);
}



void Widget::on_btnMount_2_clicked()
{
    qDebug() << "on_pushButton_clicked = " ;

    QString processName = "app.exe";
    QString command1 = "tasklist";
    QProcess process;
    QStringList arguments1;
    arguments1 << "/FI" << QString("IMAGENAME eq %1").arg(processName);

    process.start(command1, arguments1);
    process.waitForFinished();
    QByteArray output = process.readAllStandardOutput();
    QString outputStr = QString::fromLocal8Bit(output);

    if (outputStr.contains(processName)) {
        qDebug() << processName << "正在运行";
    } else {
        QMessageBox::information(nullptr, "失败", "还没有挂载！");
        return;
    }


    QString program = "taskkill";
    QStringList arguments;
    arguments << "/F" << "/IM" << "app.exe";


    process.start(program, arguments);
    process.waitForFinished();
    // 获取命令执行的输出结果
    output = process.readAllStandardOutput();
    QByteArray error = process.readAllStandardError();

    // 打印输出和错误信息
    qDebug() << "Output:" << output;
    qDebug() << "Error:" << error;
    QMessageBox::information(nullptr, "成功", "操作成功完成！");



    ui->comboBox_Upan->clear();
    Widget::MountPathList.clear();
    cust->close();

}
/*检测U盘是否卸载*/
bool Widget::conditionIsMet(){
    QString processName = "app.exe";
    QString command1 = "tasklist";
    QProcess process;
    QStringList arguments1;
    arguments1 << "/FI" << QString("IMAGENAME eq %1").arg(processName);

    process.start(command1, arguments1);
    process.waitForFinished();
    QByteArray output = process.readAllStandardOutput();
    QString outputStr = QString::fromLocal8Bit(output);

    if (outputStr.contains(processName)) {
        qDebug() << processName << "正在运行";
        return true;
    } else {

        return false;
    }
}

/*重写关闭事件*/
void Widget::closeEvent(QCloseEvent *event)
{
    // 进行条件判断
    if (!conditionIsMet()) {
        // 条件满足，关闭窗口
        event->accept();
    } else {
        // 条件不满足，忽略关闭事件
        QMessageBox::information(nullptr, "失败", "关闭软件前请卸载！");
        event->ignore();
    }
}

